<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="新闻标题" prop="newsTitle">
        <el-input v-model="queryParams.newsTitle" placeholder="请输入新闻标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select v-model="queryParams.enabled" @keyup.enter.native="handleQuery">
          <el-option label="全部" :value="undefined"></el-option>
          <el-option v-for="(label, index) in status" :key="index" :label="label" :value="index">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="添加日期" prop="createTime">
        <el-date-picker v-model="dateRange" style="width: 320px" type="datetimerange" align="right"
          start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['news:news:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['news:news:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <!-- <el-table-column label="封面图片" align="center" prop="cover" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50"/>
        </template>
</el-table-column> -->
      <el-table-column label="新闻标题" align="center" prop="newsTitle" />
      <el-table-column label="新闻说明" align="center" prop="newsDiscription" />
      <el-table-column label="状态" align="center">

        <template slot-scope="scope">
          <el-switch v-model="scope.row.enabled" @change="(value) => changeStatus(value, scope.$index, scope.row)"
            :active-value="1" :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">

        <template slot-scope="scope">
          <span>{{ (scope.row.createTime) | timestampToDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['news:news:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['news:news:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改新闻对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

    </el-dialog>
  </div>
</template>

<script>
import { listNews, delNews, updateNews } from "@/api/news/news";
import { OPEN_OR_CLOSE } from "@/constant/const";
import { timestampToDate } from '@/utils/time';

export default {
  name: "News",
  filters: {
    timestampToDate
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      dateRange: [],
      status: OPEN_OR_CLOSE,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 新闻表格数据
      newsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        newsTitle: null,
        enabled: null,
        updateTime: null
      },
      isSearch: false
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    changeStatus(value, index, row) {
      updateNews({
        id: row.id,
        enabled: value
      }).then(res => {
        this.$message.success('修改成功')
        this.newsList[index].enabled = value;
      })

    },

    /** 查询新闻列表 */
    getList() {
      let params = {}
      if (this.isSearch) {
        params = Object.assign({}, this.queryParams)
      }else{
        params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        }
      }
      this.loading = true;
      listNews(params).then(response => {
        this.newsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.isSearch = true;
      if (this.dateRange && 0 < this.dateRange.length) {
        this.queryParams.params = {
          startTime: new Date(this.dateRange[0]) / 1000,
          endTime: new Date(this.dateRange[1]) / 1000
        }
      }else{
        delete this.queryParams.params;
      }

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      delete this.queryParams.params;
      this.queryParams.pageNum = 1;
      this.isSearch = false;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: "/news/add"
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      sessionStorage.setItem("news", JSON.stringify(row));
      console.log("id: ", row.id);
      this.$router.push({
        path: `/news/edit/${row.id}`
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除新闻编号为"' + ids + '"的数据项？').then(function () {
        return delNews(ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
        
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('news/news/export', {
        ...this.queryParams,
        ids: this.ids.length? this.ids : undefined
      }, `news_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
